<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="工单名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入工单名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="工单类型" prop="type">
        <el-select v-model="queryParams.type" placeholder="请选择工单类型" class="width_100" @change="handleQuery">
          <el-option
            v-for="item in orderTypeList"
            :key="item.dictCode"
            :label="item.dictValue"
            :value="item.dictCode">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="工单状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择工单状态" class="width_100" @change="handleQuery">
          <el-option
            v-for="item in orderStatusList"
            :key="item.key"
            :label="item.label"
            :value="item.key">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

   <!-- <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['workOrder:myDeal:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['workOrder:myDeal:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['workOrder:myDeal:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['workOrder:myDeal:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>-->

    <el-table v-loading="loading" :data="myDealList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="工单编号" align="center" prop="workNumber" width="140"/>
<!--      <el-table-column label="项目代码" align="center" prop="projectCode" width="130"/>-->
      <el-table-column label="工单名称" align="center" prop="name"  />
      <el-table-column label="工单类型" align="center" prop="type" width="230">
        <template slot-scope="scope">
          <span>{{orderTypeObject[scope.row.type]}}</span>
        </template>
      </el-table-column>
<!--       <el-table-column label="工单内容" align="center" prop="contents" />-->
      <el-table-column label="计划完成时间" align="center" prop="planTime" width="100">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.planTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="处理人" align="center" prop="dealPerson" width="80">
        <template slot-scope="scope">
          <span v-if="dealPersonList.indexOf(scope['row']['dealPerson']) != '-1'">{{personObject[scope.row.dealPerson]}}</span>
          <span v-else>{{scope.row.dealPerson}}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="处理记录" align="center" prop="dealLog" /> -->
      <el-table-column label="状态" align="center" prop="status" width="140">
        <template slot-scope="scope">

          <el-tag type="info" v-if="scope.row.status == 1">处理中</el-tag>
          <el-tag type="success" v-else-if="scope.row.status == 2">已完成</el-tag>
          <el-tag type="warning" v-else-if="scope.row.status == 3">已延期</el-tag>
          <el-tag type="danger" v-else-if="scope.row.status == 4">已关闭</el-tag>
        </template>
      </el-table-column>
<!--      <el-table-column label="工单来源" align="center" prop="origin" width="120" />-->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="230px">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="check(scope.row.id)"
          >查看</el-button>

          <el-button
            v-if="scope.row.status == 1 && scope.row.dealPerson == username||scope.row.status == 3"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['workOrder:myOrder:edit']"
          >处理</el-button>

          <el-button
            v-if="scope.row.status == 1 && scope.row.dealPerson == username ||scope.row.status == 3"
            size="mini"
            type="text"
            icon="el-icon-share"
            @click="transfer(scope.row.id, scope.row.workNumber)"
          >转单</el-button>

          <el-button
            v-if="scope.row.status == 1 && scope.row.dealPerson == username ||scope.row.status == 3"
            size="mini"
            type="text"
            icon="el-icon-circle-check"
            @click="finish(scope.row.workNumber)"
          >完成</el-button>

     <!--     <el-button
            v-if="scope.row.status == 1 && scope.row.dealPerson == username"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>

          <el-button
            v-if="scope.row.status == 1 && scope.row.dealPerson == username"
            size="mini"
            type="text"
            icon="el-icon-circle-close"
            @click="close(scope.row.workNumber)"
          >关闭</el-button>-->
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改我处理的对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body @close="cancel">
      <el-form ref="form" :model="form" :rules="rules" label-width="130px">

        <el-form-item label="工单编号" prop="workNumber">
          <el-input v-model="form.workNumber" placeholder="请输入工单编码"  :disabled="checkDisabled || editDisabled"/>
        </el-form-item>
        <el-form-item label="工单名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入工单名称"  :disabled="displays"/>
        </el-form-item>
        <el-form-item label="工单类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择工单类型" class="width_100" :disabled="displays">
            <el-option
              v-for="item in orderTypeList"
              :key="item.dictCode"
              :label="item.dictValue"
              :value="item.dictCode">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="工单内容" prop="contents">
          <el-input v-model="form.contents" type="textarea" placeholder="请输入内容" :autosize="{ minRows: 2, maxRows: 6}" :disabled="displays"/>
        </el-form-item>
        <el-form-item label="计划完成时间" prop="planTime">
          <el-date-picker clearable :disabled="displays"
            v-model="form.planTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择计划完成时间">
          </el-date-picker>
        </el-form-item>
       <!-- <el-form-item label="处理人" prop="dealPerson">
          <el-input v-model="form.dealPerson" placeholder="请输入处理人" />
        </el-form-item>-->
        <el-form-item label="处理记录" prop="dealLog">
          <el-input v-model="form.dealLog" type="textarea" :autosize="{ minRows: 6, maxRows: 6 }" placeholder="请输入内容"  :disabled="checkDisabled"/>
        </el-form-item>
       <!-- <el-form-item label="工单来源" prop="origin">
          <el-input v-model="form.origin" placeholder="请输入工单来源" />
        </el-form-item>-->
        <el-form-item label="工单附件上传" prop="orderFile">
          <!-- 文件列表 -->
          <div class="upload-file-list el-upload-list el-upload-list--text" >
            <div :key="file.url" class="el-upload-list__item ele-upload-list__item-content" v-for="(file, index) in fileList" style="display: flex;justify-content:  space-between">
              <el-link :underline="false" >
                <span class="el-icon-document" @click="downloadFile(file.url, file.name)"> {{ file.name }} </span>
              </el-link>
              <!-- <div class="ele-upload-list__item-content-action">
                <el-link :underline="false" @click="handleDelete(index)" type="danger" v-if="!checkDisabled">删除</el-link>
              </div> -->
            </div>
          </div>
          <!-- <el-upload
            v-if="!checkDisabled"
            class="upload-demo"
            :headers="{Authorization: Authorization}"
            :action="uploadUrl"
            :data="{workNumber: form.workNumber, projectCode: currentProject}"
            name="file"
            :on-success="handleSuccess"
            :show-file-list="false"
            :file-list="fileList">
            <el-button size="small" type="primary">上传附件</el-button>
          </el-upload> -->
        </el-form-item>
        <el-form-item label="处理过程附件上传" prop="processFile">
          <div class="upload-file-list el-upload-list el-upload-list--text" >
            <div :key="file.url" class="el-upload-list__item ele-upload-list__item-content" v-for="(file, index) in fileProcessList" style="display: flex;justify-content:  space-between">
              <el-link :underline="false" >
                <span class="el-icon-document" @click="downloadFile(file.url, file.name)"> {{ file.name }} </span>
              </el-link>
              <div class="ele-upload-list__item-content-action">
                <el-link :underline="false" @click="handleProcessDelete(index)" type="danger" v-if="!checkDisabled">删除</el-link>
              </div>
            </div>
          </div>
          <el-upload
            v-if="form.status != '4' && !checkDisabled"
            class="upload-demo"
            :headers="{Authorization: Authorization}"
            :action="uploadUrl"
            :data="{workNumber: form.workNumber,projectCode: currentProject}"
            name="file"
            :file-list="fileProcessList"
            :on-success="processHandleSuccess"
            :show-file-list="false"
            multiple>
            <el-button size="small" type="primary">上传附件</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item v-if="form.id && checkDisabled" class="table-diy" label="工单流转记录" label-position="left" label-width="100px">
        </el-form-item>
        <el-table v-if="checkDisabled" :data="form.orderLogs" style="width: 100%">
          <el-table-column prop="contents" align="center" label="处理操作" />
            <el-table-column prop="createTime" align="center" label="日期" width="100"/>
            <el-table-column prop="createBy" align="center" label="操作人" width="90"/>
            <el-table-column prop="remark" align="left" label="备注" width="150" />
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" v-if="type != 'view'">暂存</el-button>
        <el-button type="success" @click="finish(form.workNumber)" v-if="type != 'view'">完成</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>

    </el-dialog>

    <!--转单-->
    <el-dialog title="转单" :visible.sync="transferVisible" width="500px" append-to-body>
      <el-form ref="transferForm" :model="transferForm" :rules="transferRules" label-width="130px">
        <el-form-item label="请选择接单人" prop="dealPerson">
          <el-select v-model="transferForm.dealPerson" placeholder="请选择接单人" class="width_100">
            <el-option
              v-for="item in transferList"
              :key="item.userName"
              :label="item.nickName"
              :value="item.userName">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="transferForm.remark" type="textarea" placeholder="请输入备注"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitTransferForm">确 定</el-button>
        <el-button @click="transferVisible = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listMyDeal, getMyDeal, delMyDeal, addMyDeal, updateMyDeal } from "@/api/workOrder/myDeal";
import { pickupPersonList, transferSure, finishMyOrder, closeMyOrder, updateMyOrder } from "@/api/workOrder/myOrder";
import { getToken } from '@/utils/auth';
import { getDicts } from '@/api/system/dict/data';

export default {
  name: "MyDeal",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 我处理的表格数据
      myDealList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      displays : true,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        workNumber: null,
        projectCode: null,
        name: null,
        type: null,
        contents: null,
        planTime: null,
        dealPerson: null,
        dealLog: null,
        status: null,
        origin: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      orderTypeList: [
          /*{
              key: '0',
              label: '项目运维工单'
          },
          {
              key: '1',
              label: '系统工单'
          },
          {
              key: '2',
              label: '设备更换工单'
          },
          {
              key: '3',
              label: '需求工单'
          }*/
      ],
      orderTypeObject: {},
      orderStatusList: [
          {
              key: '1',
              label: '处理中'
          },
          {
              key: '2',
              label: '已完成'
          },
          {
              key: '3',
              label: '已延期'
          },
          {
              key: '4',
              label: '已关闭'
          }
      ],
      Authorization: 'Bearer ' + getToken(),
      checkDisabled: false,
      uploadUrl: process.env.VUE_APP_BASE_API+ '/common/uploadWorkOrderFile',
      type: 'add',
      editDisabled: false,
      username: '',
      transferForm: {},
      transferVisible: false,
      transferRules: {
          dealPerson: [
              { required: true, message: '请选择接单人', trigger: 'change' }
          ],
      },
      transferList: [],
      personObject: {},
      dealPersonList: [],
      fileList: [],
      fileProcessList: []
    };
  },
  props: ['currentProject'],
  mounted() {
    this.getList();
    this.getPersonList();
    this.username = this.$store.state.user.name;
    this.getOrderTypeList();
  },
  methods: {
    downloadFile(url, fileName) {
      const xhr = new XMLHttpRequest();
      xhr.open('GET', url, true);
      xhr.responseType = 'blob';

      xhr.onload = function() {
        if (xhr.status === 200) {
          const blob = new Blob([xhr.response], { type: 'application/octet-stream' });
          const downloadUrl = URL.createObjectURL(blob);

          const link = document.createElement('a');
          link.href = downloadUrl;
          link.download = fileName;
          link.click();

          URL.revokeObjectURL(downloadUrl);
        }
      };

      xhr.send();
    },
    transformTypeObject() {
      let map = new Map();
      this.orderTypeList.forEach((d) => {
        map.set(d.dictCode, d.dictValue);
      });
      this.orderTypeObject = Object.fromEntries(map);
    },
    getOrderTypeList(){
      let oderTypeName = this.currentProject+"_gdlx";
      console.log(oderTypeName)
      getDicts(oderTypeName).then(response => {
        this.orderTypeList= response.data;
        this.transformTypeObject();
      })
    },
    /** 查询我处理的列表 */
    getList() {
      this.loading = true;
      this.queryParams.projectCode = this.currentProject;
      listMyDeal(this.queryParams).then(response => {
        this.myDealList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
      this.fileList = [];
      this.fileProcessList = [];
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        workNumber: null,
        projectCode: null,
        name: null,
        type: null,
        contents: null,
        planTime: null,
        dealPerson: null,
        dealLog: null,
        status: null,
        origin: null,
        createTime: null,
        createBy: null,
        updateTime: null,
        updateBy: null
      };
      this.resetForm("form");
      this.checkDisabled = false;
      this.editDisabled = false;
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.type = 'add';
      this.title = "添加我处理的";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getMyDeal(id).then(response => {
        this.form = response.data;
        for (const oderType of this.orderTypeList) {
          if (this.form.type==oderType.dictCode){
            this.form.type=oderType.dictValue;
            break;
          }
        }
        if(this.form.orderEnclosureList != null && this.form.orderEnclosureList.length > 0) {
            let files = [];
            let processFiles = [];
            this.form.orderEnclosureList.forEach((d) => {
              if(d.type == 1) {
                  files.push(d);
              }else if(d.type != 0) {
                  processFiles.push(d);
              }
            });
            this.fileList = files;
            this.fileProcessList = processFiles;
        }
        this.editDisabled = true;
        this.open = true;
        this.type = 'edit';
        this.title = "修改我处理的";
      });
    },
    getKeyByValue(value) {
      return Object.keys(this.orderTypeObject).find(key => this.orderTypeObject[key] === value);
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.projectCode = this.currentProject;
          this.form.orderEnclosureList = this.fileList.concat(this.fileProcessList);
          let form2 = Object.assign({}, this.form);
          if(!(typeof this.form.type === 'number')){
            form2.type = this.getKeyByValue(this.form.type)
          }
          if (this.form.id != null) {
            updateMyOrder(form2).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
              this.resetList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('删除后将同步删除工单内附件，确认删除？').then(function() {
        return delMyDeal(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('workOrder/myDeal/export', {
        ...this.queryParams
      }, `myDeal_${new Date().getTime()}.xlsx`)
    },
    resetList() {
      this.fileList = []
      this.fileProcessList = []
    },
    // // 删除文件
    // handleDelete(index) {
    //     this.fileList.splice(index, 1);
    // },
    // 删除文件
    handleProcessDelete(index) {
        this.fileProcessList.splice(index, 1);
    },
    //工单附件上传
    handleSuccess(res, file) {
        console.log(res)
        if(res.code == 200) {
            this.fileList.push({
                name: res.originalFilename,
                workNumber: this.form.workNumber,
                type: 0,
                url: res.url
            });

            //this.fileList = this.fileList.concat(this.form.orderEnclosureList);
        }
    },
    //处理过程附件上传
    processHandleSuccess(res, file) {
        console.log(res)
        if(res.code == 200) {
            this.fileProcessList.push({
                name: res.originalFilename,
                workNumber: this.form.workNumber,
                type: this.checkFileType(res.originalFilename),
                url: res.url
            });
            //this.fileProcessList = this.fileProcessList.concat(this.form.orderEnclosureList);
        }
    },
    // 验证文件类型
    checkFileType(fileName) {
      const extension = fileName.split('.').pop().toLowerCase();
      switch (extension) {
        case 'jpg':
        case 'jpeg':
        case 'png':
        case 'gif':
          return 2; // 图片类型，返回数字2
        case 'pdf':
        case 'doc':
        case 'docx':
        case 'txt':
        return 3; // 文档类型，返回数字3
        default:
          return 4; // 其他类型，返回数字4
      }
    },
    //查看
    check(id) {
        getMyDeal(id).then(response => {
          console.log('response', response)
            this.form = response.data;
          for (const oderType of this.orderTypeList) {
            if (this.form.type==oderType.dictCode){
              this.form.type=oderType.dictValue;
              break;
            }
          }
            if(this.form.orderEnclosureList != null && this.form.orderEnclosureList.length > 0) {
                let files = [];
                let processFiles = [];
                this.form.orderEnclosureList.forEach((d) => {
                    if(d.type == 1) {
                        files.push(d);
                    }else if(d.type != 0) {
                        processFiles.push(d);
                    }
                });
                this.fileList = files;
                this.fileProcessList = processFiles;
            }
            this.open = true;
            this.type = 'view';
            this.title = "查看我处理的";
            this.checkDisabled = true;
        });
    },
    getPersonList() {
        if(this.currentProject != '') {
            pickupPersonList(this.currentProject).then(res => {
                if(res.code == 200) {
                    if(res.data.length > 0) {
                        let map = new Map();
                        res['data'].forEach((d) => {
                            map.set(d.userName, d.nickName);
                        });
                        this.personObject = Object.fromEntries(map);
                        this.transferList = res.data;
                        this.dealPersonList = Object.keys(this.personObject);
                    }
                }
            })
        }
    },
    //转单
    transfer(id, workNumber) {
      // 根据这个id 查找对应 worknumber
      // 将查找到res.data.workNumber 赋值 然后载请求
      this.form.workNumber = workNumber;
        this.transferVisible = true;
        this.id = id;
    },
    //转单确认
    submitTransferForm() {
        this.$refs['transferForm'].validate((valid) => {
            if(valid) {
                this.transferForm.id = this.id;
                this.transferForm.workNumber = this.form.workNumber;

              console.log("传递的from为", this.transferForm)
                transferSure(this.transferForm).then(res => {
                    if(res.code == 200) {
                        this.$modal.msgSuccess("转单成功");
                        this.getList();
                        this.transferVisible = false;
                    }
                })
            }
        });
    },
    //完成
    finish(number) {
        this.$confirm('确认完成该工单？', '完成提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }).then(() => {
            finishMyOrder({
                workNumber: number
            }).then(res => {
                if(res.code == 200) {
                    this.getList();
                    this.$modal.msgSuccess("完成工单成功");
                    this.open=false
                }
            });
        });
    },
    //关闭
    close(number) {
        this.$confirm('工单关闭后将转至遗留问题菜单，确认关闭？', '关闭提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }).then(() => {
            closeMyOrder({
                workNumber: number
            }).then(res => {
                if(res.code == 200) {
                    this.getList();
                    this.$modal.msgSuccess("关闭工单成功");
                }
            });
        });
    }
  }
};
</script>
<style scoped>
  .width_100 {
    width: 100%;
  }
</style>
